package com.dht.xiao.jianye.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.ImageView;

import com.dht.xiao.jianye.R;

import com.dht.xiao.jianye.base.BaseActivity;
import com.dht.xiao.jianye.base.BaseBean;
import com.dht.xiao.jianye.bean.MessageEvent;
import com.dht.xiao.jianye.bean.OrderDaoBean;
import com.dht.xiao.jianye.command.base.callback.DataPackCallback;
import com.dht.xiao.jianye.command.base.exception.ApiException;
import com.dht.xiao.jianye.command.base.serialport.SerialPortSingletonMgr;
import com.dht.xiao.jianye.command.base.serialport.ServiceType;
import com.dht.xiao.jianye.command.base.serialport.bean.InitSerialPortBean;
import com.dht.xiao.jianye.command.base.serialport.callback.BaseDataCallback;
import com.dht.xiao.jianye.command.base.serialport.callback.SerialPortCallback;
import com.dht.xiao.jianye.dialog.SureDialog;
import com.dht.xiao.jianye.dlclogfile.LogFileUtil;
import com.dht.xiao.jianye.http.MainHttp;
import com.dht.xiao.jianye.utils.DBManager;
import com.dht.xiao.jianye.utils.DiningCabinetHandleDataPack;
import com.dht.xiao.jianye.utils.Information;
import com.licheedev.myutils.LogPlus;
import com.trello.rxlifecycle2.android.ActivityEvent;

import org.greenrobot.eventbus.EventBus;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.dlc.commonlibrary.okgo.rx.OkObserver;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends BaseActivity {


    @BindView(R.id.img_floor)
    ImageView imgFloor;
    private CountDownTimer countDownTimer;
    private long advertisingTime = 1200 * 1000;

    public static int AdvertisingResultCode = 1002;
    public static int TestDelayResultCode = 1003;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
       // loadRootFragment(R.id.f_content, new VerifyFrament(), false, true);
        String ANDROID_ID =
                Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);
        if (TextUtils.isEmpty(ANDROID_ID)) {
            ANDROID_ID = Build.SERIAL;
        }
        //Information.ANDROID_ID = ANDROID_ID;//a325329dfd8a7aa
        Information.ANDROID_ID = "24e1f54d2831a4dd";//a325329dfd8a7aa
        LogFileUtil.getInstance().init(getApplicationContext(), ANDROID_ID);
        init("/dev/ttyS4", 115200);

    }


    private void init(String serialPort, int baudRate) {
        Information.SerialPort = "";
        Information.BaudRate = "";
        List<byte[]> heartCommand = new ArrayList<>();
        heartCommand.add(new byte[]{(byte) 0xA0});
        InitSerialPortBean
                mInitSerialPortBean = new InitSerialPortBean(ServiceType.AsyncServices, serialPort, baudRate, true, heartCommand);
        SerialPortSingletonMgr.get().init(mInitSerialPortBean, new BaseDataCallback() {
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            @Override
            public boolean checkData(byte[] received, int size, DataPackCallback dataPackCallback) {
                return DiningCabinetHandleDataPack.handleDataPack(byteBuffer, received, size, dataPackCallback);
            }
        }, new SerialPortCallback() {
            @Override
            public void onOpenError(String deviceAddress, int baudRate, ApiException dLCException) {

            }

            @Override
            public void onOpenSuccess() {
                Information.SerialPort = serialPort;
                Information.BaudRate = baudRate + "";
                LogPlus.e("串口打开成功");
            }
        });
    }




    Disposable mDisposable;

    /**
     * 查询数据库是否有未提交数据
     */
    public void startQueryDb(int time) {
        stopQueryDb();
        Observable.timer(time, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(Long aLong) {
                        List<OrderDaoBean> list = DBManager.getInstance(MainActivity.this).query(0);
                        if (list != null && list.size() > 0) {

                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }



    private void stopQueryDb() {
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //有按下动作时取消定时
                countDownTimercancel();
                break;
            case MotionEvent.ACTION_UP:
                //抬起时启动定时
                if (Information.isMainFragment)
                    startAD();
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    public void startAD() {
        if (countDownTimer == null) {
            countDownTimer = new CountDownTimer(advertisingTime, advertisingTime) {
                @Override
                public void onTick(long millisUntilFinished) {

                }

                @Override
                public void onFinish() {
                    if (Information.isMainFragment) {
                        showOneToast("空闲");
                        Intent intent = new Intent(MainActivity.this, AdvertisingActivity.class);
                        startActivityForResult(intent, 1001);

                    }
                }
            };
        }
        countDownTimer.start();
    }

    public void countDownTimercancel() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.d("aaa", "返回了结果:" + requestCode);

        if (resultCode == AdvertisingResultCode) {
            startAD();
            EventBus.getDefault().post(new MessageEvent(Information.eventTip));
        } else if (resultCode == TestDelayResultCode) {
            startAD();
            EventBus.getDefault().post(new MessageEvent(Information.eventTip));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopQueryDb();
        SerialPortSingletonMgr.get().stopTask();
        SerialPortSingletonMgr.get().closeSerialPort();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK ) {
            //do something.
            return true;
        } else {
            return super.dispatchKeyEvent(event);
        }
    }
}

